package cloud.tianai.ram.policy.common.comparator;

import cloud.tianai.ram.policy.common.model.dto.Effect;
import cloud.tianai.ram.policy.common.model.dto.Statement;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * @Author: 天爱有情
 * @date 2022/3/21 16:07
 * @Description 默认Statement排序
 */
public class DefaultStatementComparator implements StatementComparator {

    public static final StatementComparator INSTANCE = new DefaultStatementComparator();

    @Override
    public int compare(Statement o1, Statement o2) {
        Effect effect1 = o1.getEffect();
        Effect effect2 = o2.getEffect();
        if (!Objects.equals(effect1, effect2)) {
            if (Effect.Deny.equals(effect1)) {
                return -1;
            } else if (Effect.Deny.equals(effect2)) {
                return 1;
            }
        }
        return Integer.compare(o2.getResourceList().size(), o1.getResourceList().size());
    }

    public void sortResource(List<String> resourceList) {
        if (resourceList == null || resourceList.size() <= 1) {
            return;
        }
        resourceList.sort(Comparator.comparingInt(String::length));
    }

    public void sortAction(List<String> actionList) {
        if (actionList == null || actionList.size() <= 1) {
            return;
        }
        actionList.sort(Comparator.comparingInt(String::length));
    }

    @Override
    public void sort(List<Statement> statements) {
        if (ObjectUtils.isEmpty(statements)) {
            return;
        }
        if (statements.size() > 1) {
            statements.sort(this);

        }
        for (Statement statement : statements) {
            List<String> resourceList = statement.getResourceList();
            // 排序resource， 从小到大
            if (!ObjectUtils.isEmpty(statements) && resourceList.size() > 1) {
                sortResource(resourceList);
            }
            List<String> actionList = statement.getActionList();
            // 排序action，从小到大
            if (!ObjectUtils.isEmpty(statements) && actionList.size() > 1) {
                sortAction(actionList);
            }
        }
    }
}
